<?php
class model_train extends framework_base_model {
	//批量导入字段
	private static $_batch_keywords = array(
			'area_id','area_station','author','editer'
		);
	private static $_betch_max = 299;
	/**
	 * @desc 添加地区
	 * @param array 
	 * @return number
	 */
	public static function train_add($data) {
    	if(!is_array($data)) {
    		return 0;
    	}
    	try{
    		$sql = "insert into `weixin_area_train` set ";
    		$binds = array();
    		foreach ($data as $k => $v) {
    			$sql .= '`' . $k . '`=:' . $k . ',';
    			$binds[':' . $k] = $v;
    		}
    		$sql .= 'raw_add_time=NOW()';
    		$arr=self::DB() -> dbh -> prepare($sql);
    		$rel = $arr->execute($binds);
    		if($rel == TRUE) {
    			return self::DB()->dbh->lastInsertId();
    		} else {
    			return 0;
    		}
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return 0;
    	}
    }
    /*
     * 判断该汽运地址是否还存在
     */
    public static function train_exists($area_id, $area_station, $id = 0) {
    	$info = array();

    	$sql = "select `area_train_id` from `weixin_area_train` where `area_id` = :area_id and `area_station` = :area_station and `delete_flag` = 0 ";
		$binds[":area_id"] = $area_id;
		$binds[":area_station"] = $area_station;
		if(!empty($id)){
			$sql .= " and `area_train_id` != :area_train_id";
			$binds[":area_train_id"] = $id;
		}
    	try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute($binds);
    		$info = $st -> fetch();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
    	return $info;
    }
	/*
     * 根据id是否存在该分类名称
     */
    public static function get_train_by_id($id) {
    	$info = array();
		$id = intval($id);
    	if(empty($id)) {
    		return $info;
    	}
    	$sql = "select b.`area_train_id`,a.`province`,a.`city`,a.`author`,a.`editer`,a.`raw_add_time`,b.`area_station` from `weixin_area` as a right join `weixin_area_train` as b on a.`area_id` = b.`area_id` where b.`delete_flag` = 0 and b.`area_train_id` = :area_train_id";
    	try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute(array(":area_train_id" => $id));
    		$info = $st -> fetch();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
    	return $info;
    }
    /**
     * @desc 更新分类
     * @param unknown $id
     * @param unknown $data
     * @return unknown|number
     */
    public static function update_train_info($id,$data) {
    	try{
    		$sql = 'UPDATE `weixin_area_train` SET ';
    		$binds = array();
    		foreach ($data as $k => $v) {
    			$sql .= '`' . $k . '`=:' . $k . ',';
    			$binds[':' . $k] = $v;
    		}
    		$ids = implode(',',$id);
    		$sql = trim($sql,',');
    		$sql .= ' WHERE `area_train_id` in ('.$ids.')';
    		$stm=self::DB() -> dbh -> prepare($sql);
    		$rel = $stm->execute($binds);
    		$rowCount = $stm -> rowCount();
    		return $rowCount;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return -1;
    	}
    }
    /**
     * 获取大分类列表
     * @param number $nextNum
     * @param number $pagesize
     * @param unknown $condition
     * @return unknown|Ambigous <number, unknown>
     */
    public static function get_train_list($nextNum = 0,$pagesize = 0,$condition = array()) {
    	$sql = "select b.`area_train_id`,a.`province`,a.`city`,b.`author`,b.`editer`,b.`raw_add_time`,b.`area_station` from `weixin_area` as a right join `weixin_area_train` as b on a.`area_id` = b.`area_id` where b.`delete_flag` = 0 ";
		$where = "";
    	if(is_array($condition)&& count($condition)>0){
    		if(isset($condition['province'])) {
    			$where .= " and a.`province` like '%{$condition['province']}%'";
    		}
			if(isset($condition['city'])) {
    			$where .= " and a.`city` like '%{$condition['city']}%'";
    		}
			if(isset($condition['area_station'])) {
    			$where .= " and b.`area_station` like '%{$condition['area_station']}%'";
    		}
			/*if(isset($condition['port_dest'])) {
    			$where .= " and b.`port_dest` like '%{$condition['port_dest']}%'";
    		}*/
    	}
    	$where .= " order by b.`area_train_id` desc";
    	$limit = "";
        if($pagesize != 0 ){
    		$limit = " limit {$nextNum},{$pagesize}";
    	}
    	$result = array();
    	try {
    		$st = self::DB()->dbh->prepare($sql.$where.$limit);
    		$st->execute();
    		$result = $st->fetchAll();
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		$result = array();
    	}
		
		$sql = "select count(b.`area_train_id`) from `weixin_area` as a right join `weixin_area_train` as b on a.`area_id` = b.`area_id` where b.`delete_flag` = 0 {$where}";
		$binds2 = array();
    	try {
    		$st = self::DB()->dbh->prepare($sql);
    		$st->execute($binds2);
    		$count = $st->fetchColumn();
    		$result['count'] = $count;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		$result['count'] = 0;
    	}		
		return $result;
    }
	/*
	* @desc 批量写入地址
	* @author kevin wang
	* @param array
	* @return boolean
	*
	*/
	public static function batch_insert_train(array $data){
		if(empty($data)){
			return false;
		}
		try{
			$sql = "";
			$bind = array();
			$i = 0;
			foreach($data as $value){
				if(empty($value[0]) || empty($value[1])){
					continue;
				}
				$area = model_area::privince_exists($value[0], $value[1]);
				if(empty($area)){
					$area['sortkey'] = framework_static_pinyin::transform($value[0].$value[1]);
					$area['province'] = $value[0];
					$area['city'] = $value[1];
					$area['author'] = $_SESSION['admin']['username'];
					$area['editer'] = $_SESSION['admin']['username'];
					$area_id = model_area::area_add($area);
				}else{
					$area_id = $area['area_id'];
				}
				if(model_train::train_exists($area_id, $value[2], $value[3])){
					continue;
				}
				$value[0] = $area_id;unset($value[1]);
				$value = array_values($value);
				$sql .= "insert into `weixin_area_train` set ";
				foreach($value as $k=>$v){
					$key = self::$_batch_keywords[$k];
					$sql .= "`{$key}` = ?,";
					$bind[] = empty($v)?"":$v;
				}
				$sql .= '`raw_add_time` = NOW();';
				$i++;
				if($i > self::$_betch_max){
					$sqls[] = $sql;
					$binds[] = $bind;
					$bind = array();
					$sql = "";
					$i = 0;
				}
				
			}
			//处理最后一个
			if(!empty($sql)){
				$sqls[] = $sql;
				$binds[] = $bind;
			}

			$pdo = self::DB() -> dbh;

			foreach($sqls as $key => $sqlv){
				$stm = $pdo -> prepare($sqlv);
    			$stm -> execute($binds[$key]);
			}
			
			return true;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return false;
    	}
	}
	//根据省市ID获取地区
	public static function get_area_by_province($area_id){
		$info = array();
		$sql = "select a.`province`,a.`city`,b.`area_train_id` from `weixin_area` as a,`weixin_area_train` as b where b.`area_id` = :area_id and a.`area_id` = b.`area_id` and b.`delete_flag` = 0 limit 1";
		try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute(array(':area_id'=>$area_id));
    		$info = $st -> fetch();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
		return $info;
	}
	//获取全部火运地址
	public static function get_all_train(){
		$sql = "select b.`area_train_id`,a.`province`,a.`city`,b.`author`,b.`editer`,b.`raw_add_time`,b.`area_station` from `weixin_area` as a right join `weixin_area_train` as b on a.`area_id` = b.`area_id` where b.`delete_flag` = 0";
		$return = array();
		try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute();
    		$return = $st -> fetchAll();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
		return $return;
	}
}
